<?php

namespace App\Admin\Forms\Aliyun;

use AlibabaCloud\Cdn\Cdn;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Enums\BucketType;
use App\Enums\DnsType;
use App\Enums\DomainSource;
use App\Enums\DomainType;
use App\Facades\AliyunDns;
use App\Jobs\CreateAilyunCdn;
use App\Models\Aliyun;
use App\Models\DomainPool;
use App\Models\ObjectStorageService;
use Dcat\Admin\Admin;
use Dcat\Admin\Exception\RuntimeException;
use Dcat\Admin\Http\JsonResponse;
use Illuminate\Support\Str;

class StorageDomainForm extends DcdnForm
{

    /**
     * @throws ServerException
     * @throws ClientException
     */
    public function handle(array $input): JsonResponse
    {
        if ($input['source'] == DomainSource::ALIYUN->value) {
            if (!Str::startsWith($input['rr'], '*.')) {
                $input['rr'] = '*.'.$input['rr'];
            }

            $domain = $input['rr'].'.'.$input['root'];
            if (DomainPool::where('domain', $domain)->exists()) {
                return $this->response()->error('域名必须全局唯一');
            }

            if ($input['aliyun_id'] != ObjectStorageService::ofAdmin()->find($input['oss_id'])->aliyun_id) {
                ObjectStorageService::ofAdmin()->find($input['oss_id'])->aliyun->initClient();
                try {
                    Cdn::v20180510()
                        ->verifyDomainOwner()
                        ->withDomainName(str_replace('*', '', $domain))
                        ->withVerifyType('dnsCheck')
                        ->request();
                } catch (ClientException|ServerException) {
                    $content = Cdn::v20180510()
                        ->describeVerifyContent()
                        ->withDomainName(str_replace('*', '', $domain))
                        ->request()
                        ->get('Content');

                    AliyunDns::aliyun(Aliyun::ofAdmin()->find($input['aliyun_id']))
                        ->store($input['root'], 'verification', $content, DnsType::TXT);
                }
            }
        } else {
            if (!Str::startsWith($input['domain'], '*.')) {
                return $this->response()->error('域名必须以 "*." 开头');
            }

            $domain = $input['domain'];
            if (DomainPool::where('domain', $domain)->exists()) {
                return $this->response()->error('域名必须全局唯一');
            }
        }

        $data = [
            'source' => $input['source'],
            'aliyun_id' => $input['aliyun_id'],
            'type' => DomainType::STORAGE,
            'domain' => $domain,
            'rr' => $input['rr'],
            'root' => $input['root'],
            'oss_id' => $input['oss_id'],
            'status' => $input['status'],
            'ssl' => $input['ssl'],
        ];
        if (Admin::user()->isAdministrator()) {
            $data['application_id'] = $input['application_id'];
        }

        $pool = DomainPool::ofAdmin()->create($data);

        if ($input['source'] == DomainSource::ALIYUN->value) {
            CreateAilyunCdn::dispatch($pool);
        }

        return $this->response()->success('操作成功')->refresh();
    }

    /**
     * @throws RuntimeException
     */
    public function form(): void
    {
        $this->baseForm(BucketType::STORAGE);
    }
}
